package com.lbh.music.activity;

import java.io.File;

import java.io.FileNotFoundException;
import java.util.List;

import com.lbh.music.sava.MusicNum;
import com.lbh.music.service.MusicService;
import com.lbh.music.service.SleepService;
import com.lbh.music.service.VolumService;
import com.lbh.music.service.WidgetFrontService;
import com.lbh.music.service.WidgetNextService;
import com.lbh.music.service.WidgetPlayService;
import com.lbh.music.ui.MyImageView;
import com.lbh.music.utils.ToTime;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.lbh.music.R;

/**
 * 程序首页
 * 
 */

public class main extends Activity {
	public static final String REMEMBER_USERID_KEY9 = "remember9"; // 记住播放标识
	private ImageButton play_main; // 播放|暂停
	private TextView musicname_main, main_singer; // 音乐，歌手
	private RelativeLayout relative_main;
	ToTime toTime; // 转换时间
	private Close close; // 退出广播
	private List<Music> lists;
	private MyCompletionListner2 completionListner2;
	private MyProgressBroadCa receiver;
	SharedPreferences localSharedPreferences;
	private Animation myAnimation;
	static ImageView mainindexback;
	int aaa;
	TextView indexmusicnum, indexsingernum;
	MyImageView indexmusic, indexsinger, indexlist, indexonline;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		requestWindowFeature(Window.FEATURE_NO_TITLE); // 去掉程序标题栏
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		close = new Close(); // 关闭程序广播
		IntentFilter filter22 = new IntentFilter("com.sleep.close");
		this.registerReceiver(close, filter22);
		toTime = new ToTime();

		findviews(); // 初始化views
		completionListner2 = new MyCompletionListner2();
		IntentFilter filter21 = new IntentFilter("com.cn.musicserviceplayer");
		this.registerReceiver(completionListner2, filter21);

		receiver = new MyProgressBroadCa();
		IntentFilter filter = new IntentFilter("cn.com.karl.progress");
		this.registerReceiver(receiver, filter);

		lists = MusicList.getMusicData(this);
		localSharedPreferences = getSharedPreferences("music", 0);

		// 注册Btn点击事件
		relative_main.setOnClickListener(new OnClickListener());
		indexsinger.setOnClickListener(new OnClickListener());
		indexmusic.setOnClickListener(new OnClickListener());
		indexlist.setOnClickListener(new OnClickListener());
		indexonline.setOnClickListener(new OnClickListener());
		play_main.setOnClickListener(new OnClickListener());

		run = true;
		handler.postDelayed(task, 10);
	}

	/**
	 * 动态设置背景
	 */
	private void setb() {
		Uri uri = Uri.parse(localSharedPreferences.getString("background", ""));
		if (!uri.equals("")) {
			ContentResolver contentResolver = this.getContentResolver();
			Bitmap bitmap = null;
			try {
				bitmap = BitmapFactory.decodeStream(contentResolver
						.openInputStream(uri));
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
			mainindexback.setImageBitmap(bitmap);
			mainindexback.setVisibility(View.VISIBLE);
			mainindexback.startAnimation(myAnimation);
		} else {
		}
	}

	private void findviews() {
		myAnimation = AnimationUtils.loadAnimation(this, 0x7f040001);
		indexmusic = (MyImageView) this.findViewById(R.id.indexmusic);
		indexsinger = (MyImageView) this.findViewById(R.id.indexsingeraaa);
		indexlist = (MyImageView) this.findViewById(R.id.indexlist);
		indexonline = (MyImageView) this.findViewById(R.id.indexonline);

		indexmusicnum = (TextView) this.findViewById(R.id.indexmusicnum);
		indexsingernum = (TextView) this.findViewById(R.id.indexsingernum);
		play_main = (ImageButton) this.findViewById(R.id.play_main);
		mainindexback = (ImageView) this.findViewById(R.id.mainindexbac);
		musicname_main = (TextView) this.findViewById(R.id.musicname_main);
		relative_main = (RelativeLayout) this
				.findViewById(R.id.relative_mainindex);
		main_singer = (TextView) this.findViewById(R.id.main_singer);
	}

	@Override
	protected void onResume() {
		if (MusicNum.getbtn(18)) {
			setb();
			MusicNum.putusbtn(18, false);
		}
		super.onResume();
	}

	private class MyCompletionListner2 extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			int id = intent.getIntExtra("_id", MusicService._id);
			if (id <= lists.size()) {
				Music m = lists.get(id);
				musicname_main.setText(m.getTitle());
				if (m.getSinger().equals("未知艺术家")) {
					main_singer.setText("music");
				} else {
					main_singer.setText(m.getSinger());
				}
				play_main.setBackgroundResource(R.drawable.pause1); // 设置为暂停按钮
			}
		}
	}

	@SuppressLint("ShowToast")
	@Override
	protected void onStart() {
		Log.v("main", "main:onstart(): " + lists.size());
		indexmusicnum.setText("歌曲 | " + String.valueOf(lists.size()));
		indexsingernum.setText("歌手 | " + String.valueOf(lists.size() / 4 * 3));
		if (MusicService.nowplay) {
			play_main.setBackgroundResource(R.drawable.pause1);
			try {

				Music m = lists.get(MusicService._id);
				musicname_main.setText(lists.get(MusicService._id).getTitle());
				if (m.getSinger().equals("未知艺术家")) {
					main_singer.setText("music");
				} else {
					main_singer.setText(m.getSinger());
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			play_main.setBackgroundResource(R.drawable.play1);
			if (MusicService.player == null) {
				int a = Integer.valueOf(localSharedPreferences.getInt(
						"currentId", 0));
				try {
					Music mm = lists.get(a);
					musicname_main.setText(mm.getTitle());
					if (mm.getSinger().equals("未知艺术家")) {
						main_singer.setText("music");
					} else {
						main_singer.setText(mm.getSinger());
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			} else {
				try {
					Music mmm = lists.get(MusicService._id);
					musicname_main.setText(mmm.getTitle());
					if (mmm.getSinger().equals("未知艺术家")) {
						main_singer.setText("music");
					} else {
						main_singer.setText(mmm.getSinger());
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}

		}

		super.onStart();
	}

	public class Close extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			stopService();
			finish();
			play_main.setBackgroundResource(R.drawable.play1);
		}
	}

	public void stopService() {
		Log.e("Index Activity", "Index: stopService()");
		stopService(new Intent(main.this, MusicService.class));
		stopService(new Intent(main.this, SleepService.class));
		stopService(new Intent(main.this, VolumService.class));
		stopService(new Intent(main.this, WidgetNextService.class));
		stopService(new Intent(main.this, WidgetFrontService.class));
		stopService(new Intent(main.this, WidgetPlayService.class));
	}

	private long count = 0;
	private boolean run = false;

	private Handler handler = new Handler();

	private Runnable task = new Runnable() {

		public void run() {
			if (run) {
				handler.postDelayed(this, 10);
				count++;
			}
			if (count > 0) {
				setb();
				run = false;
			}
		}
	};

	@Override
	protected void onDestroy() {
		this.unregisterReceiver(close);
		this.unregisterReceiver(completionListner2);
		this.unregisterReceiver(receiver);
		super.onDestroy();
	}

	@SuppressLint("ShowToast")
	public class OnClickListener implements android.view.View.OnClickListener {

		@Override
		public void onClick(View v) {
			if (v == relative_main) {
				Intent intent3 = new Intent(main.this, MusicActivity.class);
				startActivity(intent3);
			} else if (v == play_main) { // 播放 事件
				if (lists.size() > 0) {
					Music m = lists.get(MusicService._id);
					if (MusicService.player != null
							&& MusicService.player.isPlaying()) {
						play_main.setBackgroundResource(R.drawable.play1);
					} else {
						play_main.setBackgroundResource(R.drawable.pause1);
					}
					// 播放
					Intent intents = new Intent(main.this, MusicService.class);
					intents.putExtra("play", 3);
					MusicNum.putplay(3);
					MusicNum.putisok(true);
					startService(intents);
				} else {
					Toast.makeText(getApplicationContext(), "您的播放列表为空", 1)
							.show();
				}
			} else if (v == indexmusic) { // 歌曲
				Intent intent1 = new Intent(main.this,
						com.lbh.music.activity.IMainActivity.class);
				startActivity(intent1);
			} else if (v == indexsinger) { // 歌手
				Intent intent1 = new Intent(main.this,
						com.lbh.music.activity.ArtistsActivity.class);
				startActivity(intent1);
			} else if (v == indexlist) { // 列表
				Intent intent1 = new Intent(main.this,
						com.lbh.music.activity.List.class);
				startActivity(intent1);
			} else if (v == indexonline) { // 在线
				Intent intent1 = new Intent(main.this,
						com.lbh.music.activity.Online.class);
				startActivity(intent1);
			}
		}
	}

	public class MyProgressBroadCa extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			Music m = lists.get(MusicService._id);
			if (MusicService.player != null) {
				if (MusicService.player.isPlaying()) {
					play_main.setBackgroundResource(R.drawable.pause1);
				} else {
					play_main.setBackgroundResource(R.drawable.play1);
				}
			}
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// menu.add(0,1,0,"退出"); //添加选项
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@SuppressLint("ShowToast")
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (item.getItemId() == R.id.exit) {
			Intent intent = new Intent("com.sleep.close");
			sendBroadcast(intent); // 发送退出程序广播
			finish();
		}
		// if (item.getItemId() == R.id.about) { //关于界面
		// Intent intent1 = new Intent(main.this, About.class);
		// startActivity(intent1);
		// }
		// if (item.getItemId() == R.id.deletecurrent) {
		// if (MusicService.nowplay) {
		// File f = new File(lists.get(MusicService._id).getUrl());
		// if (f.exists()) {
		// try {
		// f.delete();
		// if (MusicService.his > 0) {
		// MusicService.his -= 1;
		// }
		// } catch (Exception e) {
		// e.printStackTrace();
		// }
		// MusicNum.putint(3);
		// Intent intent = new Intent(main.this, MusicService.class);
		// MusicNum.putplay(5);
		// MusicNum.putisok(true);
		// startService(intent);
		// Toast.makeText(getApplicationContext(), "删除成功！", 1).show();
		// }
		// } else {
		// Toast.makeText(getApplicationContext(), "抱歉,当前没有歌曲在播放！", 1)
		// .show();
		// }
		// }
		if (item.getItemId() == R.id.entersleep) {
			Intent intent1 = new Intent(main.this, Sleep.class);
			startActivity(intent1);
		}
		if (item.getItemId() == R.id.menusearch) {
			Intent intent1 = new Intent(main.this, Search.class);
			startActivity(intent1);
		}
		if (item.getItemId() == R.id.setting) {
			Intent intent1 = new Intent(main.this, Setting.class);
			startActivity(intent1);
		}
		if (item.getItemId() == R.id.refresh) {
			lists = MusicList.getMusicData(this);
			Toast.makeText(getApplicationContext(), "刷新成功！", 1).show();
		}
		if (item.getItemId() == R.id.settingring) {
			if (MusicService.player == null) {
				Toast.makeText(getApplicationContext(), "当前音乐为空！", 1).show();
			} else {
				try {
					Music m = lists.get(MusicService._id);
					String path = m.getUrl();
					setMyRingtone(path);
					Toast.makeText(getApplicationContext(), "设置铃声成功！", 1)
							.show();
				} catch (Exception e) {
					e.printStackTrace();
					Toast.makeText(getApplicationContext(), "设置铃声失败！", 1)
							.show();
				}
			}
		}
		return super.onOptionsItemSelected(item);
	}

	public void setMyRingtone(String path) {
		File file = new File(path);
		ContentValues values = new ContentValues();
		values.put(MediaStore.MediaColumns.DATA, file.getAbsolutePath());
		values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/mp3");
		values.put(MediaStore.Audio.Media.IS_RINGTONE, true);
		values.put(MediaStore.Audio.Media.IS_NOTIFICATION, false);
		values.put(MediaStore.Audio.Media.IS_ALARM, false);
		values.put(MediaStore.Audio.Media.IS_MUSIC, false);
		Uri uri = MediaStore.Audio.Media.getContentUriForPath(file
				.getAbsolutePath());
		Uri newUri = this.getContentResolver().insert(uri, values);
		RingtoneManager.setActualDefaultRingtoneUri(this,
				RingtoneManager.TYPE_RINGTONE, newUri);
	}
}
